// QpskGo/qpsk_demod.go
package QpskGo

import (
	"lht-go-plugins/LhtPlugins/Algorithm/Demodulation"
)

type QPSKDemodulator struct {
	d *Demodulation.DemoQPSK
}

func NewQPSKDemodulator(param Demodulation.DemodulationInitParameter) *QPSKDemodulator {
	return &QPSKDemodulator{
		d: Demodulation.NewDemoQPSK(param),
	}
}

func (q *QPSKDemodulator) Demodulate(input []Demodulation.Complex, baseTime int64) *Demodulation.DemodulationResult {
	d := q.d
	N := len(input)

	// ==================== 1. 块滤波 ====================
	filtered := make([]Demodulation.Complex, N)
	d.BlockFilter(input, filtered)

	// ==================== 2. AGC ====================
	d.AGC(filtered)

	// ==================== 3. Costas 载波同步 ====================
	carrierOut := make([]Demodulation.Complex, N)
	d.CostasPLL(filtered, carrierOut)

	// ==================== 4. 符号同步（Gardner + 立方插值） ====================
	maxSymbols := N/4 + 100
	symbols := make([]Demodulation.Complex, 0, maxSymbols)
	nSym := d.SymbolSync(carrierOut, symbols)

	// 注意：SymbolSync 会自动 append 到 symbols 切片
	symbols = symbols[:nSym] // 裁剪到实际长度

	// ==================== 5. 差分硬判决 + 解差分 ====================
	bits := d.DiffJudgment(symbols)

	// ==================== 6. 更新累计样点数（用于 Costas 分段切换） ====================
	d.SampleCount += int64(N)

	// ==================== 7. 打包输出 ====================
	return &Demodulation.DemodulationResult{
		Burst: &Demodulation.DemodulationBurstData{
			SoftData:  symbols, // 软符号（可画星座图）
			HardBits:  bits,    // 解调出的比特流（已解差分）
			Length:    nSym,    // 本次突发符号数
			StartTime: baseTime,
		},
	}
}

// ==============================================================================
// 兼容你原来单函数风格（不推荐长期使用，但保留兼容性）
// ==============================================================================
func DemodulateOnce(param Demodulation.DemodulationInitParameter, input []Demodulation.Complex, baseTime int64) *Demodulation.DemodulationResult {
	demod := NewQPSKDemodulator(param)
	return demod.Demodulate(input, baseTime)
}
